if(!dojo._hasResource["opm.widgets.GenericForm"]){
dojo._hasResource["opm.widgets.GenericForm"] = true;
dojo.provide("opm.widgets.GenericForm");
dojo.require("dijit._Widget");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.form.NumberTextBox");
dojo.require("dijit.form.Button");
dojo.require("dijit.form.Textarea");
dojo.require("dijit.form.CheckBox");
dojo.require("dijit.form.DateTextBox");
dojo.require("dijit.form.Select");
dojo.require("dojo.io.iframe");
dojo.require("opm.widgets.GenericArrow");
dojo.require("opm.widgets.CustomDateTextBox");
dojo.declare("opm.widgets.GenericForm",dijit._Widget,
{
   actionUrl:"",
   formName:"",
   formId:"",
   title:"",
   enctype:"",
   form:null,

   ajaxCallUrl:"",
   ajaxCallType:"",

   widgetId:"",
   contentId:"",

   _postGenericData:[],
   _externalWidgets:[],
   _handleSubscribeEvent:{},
   _currentData:{},
   constructor:function(args){
      this.contentId = args.contentId;
      this.widgetId = args.id;
   },
   setAtt:function(name, value){
      this[name] = value;
   },
   getAtt:function(name){
      if (name=="fields"){
        return this.form[name];
      }
      return this._currentData[name];
   },
   getProperty:function(name){
      var commonForm = dojo.query('#'+this.contentId + ' [id="'+this.formId+'"]')[0];
      var resultElements = dojo.query('[name="'+name+'"]', commonForm);
      if (resultElements){
         var element = resultElements[0];
         if (element.getAttribute("type")=="checkbox"){
            return element.checked;
         }
         return element.value;
      }
      return null;
   },
   getWidget:function(name,type){
      var cusWidget=null;
      if ("arrow"==type){
         cusWidget=this._externalWidgets[this._parseArrowId(name)];
      }
      return cusWidget;
   },
   getJsonForm:function(){
      
   },
   setDataForm:function(args){
      var _args = (args==null)?{}:args;
      this._currentData = _args;
      this.title = _args.title ? _args.title:"";
      this.form = _args.form ? _args.form : {};
      this.actionUrl = this.form.actionUrl ? this.form.actionUrl:"";
      this.formName = this.form.formName ? this.form.formName:"";
      this.formId = this.widgetId + "_" + this.formName;
      this.enctype = this.form.enctype;
   },
   empty:function (){
      fields = this.form.fields == null ? [] : this.form.fields;
      fields = this.form.buttons == null ? fields : fields.concat(this.form.buttons);
      if (fields != null){
         for (var index=0; index<fields.length; index++){
            dijit.registry.remove(fields[index].name);
         }
      }
      this._postGenericData = [];
      this._externalWidgets = [];
   },
   createForm:function(){
      var commonForm = this;
      var args = {
         ajaxUrl: this.ajaxCallUrl,
         callback: function (data){
             commonForm.setDataForm(data);
             commonForm.show();
      }};
      OPM.callAjaxWidget(args, this.contentId, this.ajaxCallType);
   },
   show:function(){
      this.empty();
      var htmlData = this._genericForm();
      console.log('ContentId: ' + this.contentId + " ---- WidgetId: " + this.widgetId);
      dojo.html.set(dojo.byId(this.contentId),htmlData,{parseContent: true});
      this.postGeneric();
      this._publishEvent();
   },
   postGeneric:function(){
      for (var index=0; index<this._postGenericData.length; index++){
         var postData = this._postGenericData[index];
         var controlType = postData.type;
         switch (controlType){
         case "arrow":
            var arrowData = postData.value;
            arrowData.contentId = postData.contentId;
            arrowData.controlName = postData.name;
            var arrow = new opm.widgets.GenericArrow(arrowData);
            arrow.generic();
            this._externalWidgets[postData.contentId] = arrow;
            break;
         }
      }
   },
   hasError:function(errorData){
      var hasError = errorData.hasError;
      if (hasError == true){
         return true;
      }
      return false;
   },
   showError:function(errorData){
      if (this.hasError(errorData)){
         var fields = (errorData.fields==null)?[]:errorData.fields;
         for (var index=0; index<fields.length; index++){
            fieldObject = fields[index];
            var control = dojo.byId(this.formId+'_'+fieldObject.name + '.error');
            if (control != null){
               control.innerHTML = fieldObject.value;
            }
         }
      }
   },
   callSaveForm:function(callBack){
      var localForm = this;
      if (this.enctype == 'multipart/form-data'){
         dojo.io.iframe.send({
            form: localForm.formId,
            handleAs: 'json',
            load: function(data, msg) {
                if (localForm.hasError(data)){
                    if (callBack.handleError == null){
                        localForm.showError(data);
                    }else {
                        callBack.handleError(data);
                    }
                }else {
                    callBack.handleSuccess(data);
                }
            },
            error: function(type, err) {
                window.alert(err.message);
            }
        });
      }else {
          var args ={
          form: this.formId,
          callback: function (data){
             if (localForm.hasError(data)){
                if (callBack.handleError == null){
                   localForm.showError(data);
                }else {
                   callBack.handleError(data);
                }
             }else {
                callBack.handleSuccess(data);
             }
          }};
          OPM.ajaxWidget(args, this.contentId).callXhrPostForm();
      }
   },
   callSaveProperties:function(properties, callBack){
      var postTextData = "";
      for (var index=0; index<properties.length; index++){
         propertyName = properties[index];
         propertyValue = dojo.query('#'+this.contentId+' [id="'+propertyName+'"]')[0].value;
         postTextData += propertyName+"="+propertyValue;
      }
      this.callSavePostData(postTextData, callBack);
   },
   callSavePostData:function(postData, callBack){
      var localForm = this;
      var args ={
         ajaxUrl: this.actionUrl,
         postData:postData,
         callback: function (data){
         if (localForm.hasError(data)){
            if (callBack.handleError == null){
               localForm.showError(data);
            }else {
               callBack.handleError(data);
            }
         }else {
            callBack.handleSuccess(data);
         }
      }};
      OPM.ajaxWidget(args, this.contentId).callXhrPostText();
   },
   connectEvent:function(name, callBackFunction){
      var eventName = this.widgetId + "_" + name;
      if (this._handleSubscribeEvent[eventName] == null){ 
         console.log('Subscribe: ' + eventName);
         this._handleSubscribeEvent[eventName] = dojo.subscribe(eventName, function (data){
            callBackFunction(data);
         });
      }
   },
   _genericForm:function(){
      var fields = this.form.fields;
      var htmlData = "";
      if (fields != null){
         htmlData = '<div>';
         var enctypeAtt = (this.enctype == '' || this.enctype == null)?'':'enctype="' + this.enctype + '"'; 
         htmlData += '<form id="'+this.formId+'" name="'+this.formName+'" action="'+this.actionUrl+'" method="POST"'+enctypeAtt+'>';
         htmlGroup = '';
         for (var index=0; index<fields.length; index++){
            var control = fields[index];
            var controlName = control.name;
            var controlLabel = control.label==null?'':control.label;
            var controlType = control.type;
            var controlValue = control.value;
            var styleDisable = control.disable=="true"?"readonly=true":"";
            if (controlName == "layout" && controlType == "group"){
                htmlData = htmlData + htmlGroup + ((htmlGroup=='')?'':'</fieldset>');
                htmlGroup = '<fieldset class="fieldsCollection">';
                htmlGroup += '<legend>'+control.title+'</legend>';
                htmlGroup += '<div class="dotline"></div>';
                continue;
            }else if (index == 0){
                htmlGroup = '<fieldset class="fieldsCollection">';
                htmlGroup += '<legend>'+this.title+'</legend>';
                htmlGroup += '<div class="dotline"></div>';
            }
            var controlHTML = '';
            var labelHTML = '<div class="divRow"><label for="'+controlName+'" class="label">'+controlLabel+'</label>';
            var errorHTML = '<div class="divErrors"><span id="'+this.formId+"_"+controlName+'.error" class="error"/></div></div>';
            switch (controlType){
               case "label":
                  controlHTML = labelHTML + this._parseLabelHtml(controlName, controlValue, styleDisable);
                  break;
               case "hidden":
                  controlHTML = this._parseHiddenHtml(controlName, controlValue, styleDisable);
                  break;
               case "text":
               case "0":
                  controlHTML = labelHTML + this._parseTextHtml(controlName, controlValue, styleDisable) + errorHTML;
                  break;
               case "number":
               case "1":
               case "2":
                  controlHTML = labelHTML + this._parseNumberHtml(controlName, controlValue, styleDisable) + errorHTML;
                  break;
               case "longText":
                  controlHTML = labelHTML + this._parseLongTextHtml(controlName, controlValue, styleDisable) + errorHTML;
                  break;
               case "multiText":
                  controlHTML = labelHTML + this._parseMultiTextHtml(controlName, controlValue, styleDisable, control.datasource) + errorHTML;
                  break;
               case "date":
               case "3":
                  controlHTML = labelHTML + this._parseDateHtml(controlName, controlValue, styleDisable) + errorHTML;
                  break;
               case "boolean":
               case "4":
                  controlHTML = labelHTML + this._parseBooleanHtml(controlName, controlValue, styleDisable) + errorHTML;
                  break;
               case "singleFile":
                  controlHTML = labelHTML + this._parseSingleUploadHtml(controlName, controlValue, styleDisable) + errorHTML;
                  break;
               case "arrow":
                  controlHTML = labelHTML + this._parseArrowHtml(controlName, controlValue, controlType, styleDisable) + errorHTML;
                  break;
               case "password":
                  controlHTML = labelHTML + this._parsePasswordHtml(controlName, controlValue, styleDisable) + errorHTML;
                  break;
               case "radio":
                  controlHTML = labelHTML + this._parseRadioHtml(controlName, controlValue, styleDisable, control.datasource) + errorHTML;
                  break;
            }
            htmlGroup += controlHTML;
         }
         htmlData = htmlData + htmlGroup + '</fieldset>';
         htmlData += '<fieldset class="fieldsCollection"><div class="divRow"><div class="inputButton">';
         var buttons = this.form.buttons;
         if (buttons != null){
            for (var index=0; index<buttons.length; index++){
               var button = buttons[index];
               var buttonType = (button.type == null) ? "button" : button.type;  
               htmlData += '<input id="'+button.name+'" type="'+buttonType+'" dojoType="dijit.form.Button" label="'+button.label+'"/>'; 
            }
         }
         htmlData += '</div></div></fieldset></form></div>';
      }
      return htmlData;
   },
   connectEvent:function(name, callBackFunction){
      var eventName = this.widgetId + "_" + name;
      if (this._handleSubscribeEvent[eventName] == null){ 
         console.log('Subscribe: ' + eventName);
         this._handleSubscribeEvent[eventName] = dojo.subscribe(eventName, function (data){
            callBackFunction(data);
         });
      }
   },
   _publishEvent:function(){
      var buttons = this.form.buttons == null ? [] : this.form.buttons;
      for (var index=0; index<buttons.length; index++){
         var button = buttons[index];
         var buttonId = button.name;
         var localwidgetId = this.widgetId;
         dojo.query('#'+this.contentId+' [id="'+buttonId+'"]').onclick(function(){
            var eventName = localwidgetId+"_"+this.id+'Click';
            console.log('Publish: ' + eventName);
            dojo.publish(eventName, [this]);
         });
      }
   },
   _parseLabelHtml:function(controlName, controlValue, styleDisable){
       var htmlString = '<div class="input">'+controlValue+'</div>';
       return htmlString;
   },
   _parseHiddenHtml:function(controlName, controlValue, styleDisable){
       var htmlString = '<input type="hidden" id="'+controlName+'" name="'+controlName+'" value="'+controlValue+'" '+styleDisable+'>';
       return htmlString;
   },
   _parseTextHtml:function(controlName, controlValue, styleDisable){
       var htmlString = '<div class="input"><input type="text" id="'+controlName+'" name="'+controlName+'" value="'+controlValue+'" '+styleDisable+' dojoType="dijit.form.TextBox"></div>';
       return htmlString;
   },
   _parsePasswordHtml:function(controlName, controlValue, styleDisable){
      var htmlString = '<div class="input"><input type="password" id="'+controlName+'" name="'+controlName+'" value="'+controlValue+'" '+styleDisable+' dojoType="dijit.form.TextBox"></div>';
      return htmlString;
  },
   _parseNumberHtml:function(controlName, controlValue, styleDisable){
       var htmlString = '<div class="input"><input type="text" id="'+controlName+'" name="'+controlName+'" value="'+controlValue+'" '+styleDisable+' dojoType="dijit.form.NumberTextBox" constraints="{pattern:\'###0\'}"></div>';
       return htmlString;
   },
   _parseLongTextHtml:function(controlName, controlValue, styleDisable){
       var htmlString = '<div class="input"><textarea id="'+controlName+'" name="'+controlName+'" '+styleDisable+' dojoType="dijit.form.Textarea" style="width:200px">'+controlValue+'</textarea></div>';
       return htmlString;
   },
   _parseMultiTextHtml:function(controlName, controlValue, styleDisable, dataSource){
       var htmlString = '<div class="input"><select dojoType="dijit.form.Select" name="'+controlName+'" '+styleDisable+' style="width:200px">';
       for (var indexOption=0; indexOption<dataSource.length; indexOption++){
          var option = dataSource[indexOption];
          var optionValue = option.value;
          htmlString += '<option value="'+optionValue+'" '+((optionValue==controlValue)?'selected':'')+'>'+option.label+'</option>';
       }
       htmlString += '</select></div>';
       return htmlString;
   },
   _parseRadioHtml:function(controlName, controlValue, styleDisable, dataSource){
      var htmlString = '<div class="input">';
      for (var indexOption=0; indexOption<dataSource.length; indexOption++){
         var optionValue = dataSource[indexOption];
         htmlString+='<input dojoType="dijit.form.RadioButton" type="radio" name="'+controlName+'" '+((optionValue==controlValue)?'checked':'') + ' value="'+optionValue+'"/><label>'+optionValue+'</label><br/>';
      }
      htmlString += '</div>';
      return htmlString;
  },
   _parseDateHtml:function(controlName, controlValue, styleDisable){
       var htmlString = '<div class="input"><input type="text" name="'+controlName+'" value="'+controlValue+'" '+styleDisable+' dojoType="opm.widgets.CustomDateTextBox"></div>';
       return htmlString;
   },
   _parseBooleanHtml:function(controlName, controlValue, styleDisable){
       var checkedHtml = controlValue=='true'?'checked':'';
       var htmlString = '<div class="input"><input type="checkbox" '+checkedHtml+' id="'+controlName+'" name="'+controlName+'" value="'+controlValue+'" '+styleDisable+' dojoType="dijit.form.CheckBox"></div>';
       return htmlString;
   },
   _parseSingleUploadHtml:function(controlName, controlValue, styleDisable){
       var htmlString = '<div class="input"><input name="'+controlName+'" type="file" id="'+controlName+'" /></div>';
       return htmlString;
   },
   _parseArrowHtml:function(controlName, controlValue, controlType, styleDisable){
       var arrowId = this._parseArrowId(controlName);
       this._postGenericData[this._postGenericData.length] = {name: controlName, value:controlValue, contentId:arrowId, type:controlType};
       var htmlString = '<div class="input"><div id="'+arrowId+'"></div></div>';
       return htmlString;
   },
   _parseArrowId:function(controlName){
      var arrowId = this.contentId + '_arrow_content_'+controlName;
      return arrowId;
   }
});}